package com.xdy.server.core;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: XDY.
 * @Email: 2280944114@qq.com
 * @CreateTime: 2023-03-13  15:58
 * @Description: web服务器
 * @Version: 1.0
 */
public class DyServer {

    //服务监听端口
    private int port;

    //服务套接字
    private ServerSocket serverSocket;

    //服务是否运行
    private boolean isRunning;

    public DyServer() {
        this(8888);
    }

    public DyServer(int port) {
        this.port = port;
    }

    /**
     * 启动服务
     */
    public void start() {
        try {
            //初始化配置
            WebApp.init();
            //启动服务
            serverSocket = new ServerSocket(port);
            isRunning = true;
            System.out.println("服务启动成功，监听端口：" + port);
            //接收请求
            receive();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("服务器出错啦~...");
        }
    }

    /**
     * 接收请求
     */
    public void receive() {
        while (isRunning){
            try {
                Socket client = serverSocket.accept();
                new Thread(new Dispatcher(client)).start();
            } catch (Exception e) {
                System.err.println("客户端连接出错了...");
                stop();
            }
        }
    }

    /**
     * 停止服务
     */
    public void stop() {
        isRunning = false;
        try {
            serverSocket.close();
            System.out.println("服务器已停止...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        DyServer server = new DyServer();
        server.start();
    }
}
